<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.6" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.6">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.6" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.6',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  

<meta name="description" content="基础 创建表 插入 更新 删除 修改表 查询 排序 过滤 通配符 计算字段 函数 文本处理 日期和时间处理 数值处理 汇总   分组 子查询 连接 内连接 自连接 自然连接 外连接   组合查询 视图 存储过程 游标 触发器 事务处理 字符集 权限管理   基础模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息，数据库和表都有模式。 主键的值不允许修改，也不允许复用（不能使用已经删">
<meta name="keywords" content="SQL">
<meta property="og:type" content="article">
<meta property="og:title" content="SQL基础（转）">
<meta property="og:url" content="http://7ht.gitee.io/2018/03/16/SQL基础（转）/index.html">
<meta property="og:site_name" content="HonTu&#39;s Notes">
<meta property="og:description" content="基础 创建表 插入 更新 删除 修改表 查询 排序 过滤 通配符 计算字段 函数 文本处理 日期和时间处理 数值处理 汇总   分组 子查询 连接 内连接 自连接 自然连接 外连接   组合查询 视图 存储过程 游标 触发器 事务处理 字符集 权限管理   基础模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息，数据库和表都有模式。 主键的值不允许修改，也不允许复用（不能使用已经删">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-28T03:26:35.843Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SQL基础（转）">
<meta name="twitter:description" content="基础 创建表 插入 更新 删除 修改表 查询 排序 过滤 通配符 计算字段 函数 文本处理 日期和时间处理 数值处理 汇总   分组 子查询 连接 内连接 自连接 自然连接 外连接   组合查询 视图 存储过程 游标 触发器 事务处理 字符集 权限管理   基础模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息，数据库和表都有模式。 主键的值不允许修改，也不允许复用（不能使用已经删">






  <link rel="canonical" href="http://7ht.gitee.io/2018/03/16/SQL基础（转）/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>SQL基础（转） | HonTu's Notes</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> 

<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HonTu's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一小瓶</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
          
  <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      

      
    </ul>
  

  

  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://7ht.gitee.io/2018/03/16/SQL基础（转）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Q.hongtao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/head_cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HonTu's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SQL基础（转）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-16T18:54:02+08:00">2018-03-16</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/基础知识/" itemprop="url" rel="index"><span itemprop="name">基础知识</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <!-- GFM-TOC -->
<ul>
<li><a href="#基础">基础</a></li>
<li><a href="#创建表">创建表</a></li>
<li><a href="#插入">插入</a></li>
<li><a href="#更新">更新</a></li>
<li><a href="#删除">删除</a></li>
<li><a href="#修改表">修改表</a></li>
<li><a href="#查询">查询</a></li>
<li><a href="#排序">排序</a></li>
<li><a href="#过滤">过滤</a></li>
<li><a href="#通配符">通配符</a></li>
<li><a href="#计算字段">计算字段</a></li>
<li><a href="#函数">函数</a><ul>
<li><a href="#文本处理">文本处理</a></li>
<li><a href="#日期和时间处理">日期和时间处理</a></li>
<li><a href="#数值处理">数值处理</a></li>
<li><a href="#汇总">汇总</a></li>
</ul>
</li>
<li><a href="#分组">分组</a></li>
<li><a href="#子查询">子查询</a></li>
<li><a href="#连接">连接</a><ul>
<li><a href="#内连接">内连接</a></li>
<li><a href="#自连接">自连接</a></li>
<li><a href="#自然连接">自然连接</a></li>
<li><a href="#外连接">外连接</a></li>
</ul>
</li>
<li><a href="#组合查询">组合查询</a></li>
<li><a href="#视图">视图</a></li>
<li><a href="#存储过程">存储过程</a></li>
<li><a href="#游标">游标</a></li>
<li><a href="#触发器">触发器</a></li>
<li><a href="#事务处理">事务处理</a></li>
<li><a href="#字符集">字符集</a></li>
<li><a href="#权限管理">权限管理</a><!-- GFM-TOC -->
</li>
</ul>
<h1 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h1><p>模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息，数据库和表都有模式。</p>
<p>主键的值不允许修改，也不允许复用（不能使用已经删除的主键值赋给新数据行的主键）。</p>
<p>SQL（Structured Query Language)，标准 SQL 由 ANSI 标准委员会管理，从而称为 ANSI SQL。各个 DBMS 都有自己的实现，如 PL/SQL、Transact-SQL 等。</p>
<p>SQL 语句不区分大小写，但是数据库表名、列名和值是否区分依赖于具体的 DBMS 以及配置。</p>
<p>SQL 支持以下三种注释：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># 注释</span><br><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable; <span class="comment">-- 注释</span></span><br><span class="line"><span class="comment">/* 注释1</span></span><br><span class="line"><span class="comment">   注释2 */</span></span><br></pre></td></tr></table></figure>
<h1 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h1><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> mytable (</span><br><span class="line">  <span class="keyword">id</span> <span class="built_in">INT</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  col1 <span class="built_in">INT</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="number">1</span>,</span><br><span class="line">  col2 <span class="built_in">VARCHAR</span>(<span class="number">45</span>) <span class="literal">NULL</span>,</span><br><span class="line">  col3 <span class="built_in">DATE</span> <span class="literal">NULL</span>,</span><br><span class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>));</span><br></pre></td></tr></table></figure>
<h1 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h1><p><strong>普通插入</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> mytable(col1, col2)</span><br><span class="line"><span class="keyword">VALUES</span>(val1, val2);</span><br></pre></td></tr></table></figure>
<p><strong>插入检索出来的数据</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> mytable1(col1, col2)</span><br><span class="line"><span class="keyword">SELECT</span> col1, col2</span><br><span class="line"><span class="keyword">FROM</span> mytable2;</span><br></pre></td></tr></table></figure>
<p><strong>将一个表的内容复制到一个新表</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> newtable <span class="keyword">AS</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>
<h1 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h1><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">UPDATE</span> mytable</span><br><span class="line"><span class="keyword">SET</span> <span class="keyword">col</span> = val</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">id</span> = <span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<h1 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h1><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">id</span> = <span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<p><strong>TRUNCATE TABLE</strong>  可以清空表，也就是删除所有行。</p>
<p>使用更新和删除操作时一定要用 WHERE 子句，不然会把整张表的数据都破坏。可以先用 SELECT 语句进行测试，防止错误删除。</p>
<h1 id="修改表"><a href="#修改表" class="headerlink" title="修改表"></a>修改表</h1><p><strong>添加列</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line"><span class="keyword">ADD</span> <span class="keyword">col</span> <span class="built_in">CHAR</span>(<span class="number">20</span>);</span><br></pre></td></tr></table></figure>
<p><strong>删除列</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">COLUMN</span> <span class="keyword">col</span>;</span><br></pre></td></tr></table></figure>
<p><strong>删除表</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> mytable;</span><br></pre></td></tr></table></figure>
<h1 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h1><p><strong>DISTINCT</strong></p>
<p>相同值只会出现一次。它作用于所有列，也就是说所有列的值都相同才算相同。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">DISTINCT</span> col1, col2</span><br><span class="line"><span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>
<p><strong>LIMIT</strong></p>
<p>限制返回的行数。可以有两个参数，第一个参数为起始行，从 0 开始；第二个参数为返回的总行数。</p>
<p>返回前 5 行：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">LIMIT</span> <span class="number">5</span>;</span><br></pre></td></tr></table></figure>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">LIMIT</span> <span class="number">0</span>, <span class="number">5</span>;</span><br></pre></td></tr></table></figure>
<p>返回第 3 ~ 5 行：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">LIMIT</span> <span class="number">2</span>, <span class="number">3</span>;</span><br></pre></td></tr></table></figure>
<h1 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h1><ul>
<li><strong>ASC</strong> ：升序（默认）</li>
<li><strong>DESC</strong> ：降序</li>
</ul>
<p>可以按多个列进行排序，并且为每个列指定不同的排序方式：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> col1 <span class="keyword">DESC</span>, col2 <span class="keyword">ASC</span>;</span><br></pre></td></tr></table></figure>
<h1 id="过滤"><a href="#过滤" class="headerlink" title="过滤"></a>过滤</h1><p>不进行过滤的数据非常大，导致通过网络传输了很多多余的数据，从而浪费了网络带宽。因此尽量使用 SQL 语句来过滤不必要的数据，而不是传输所有的数据到客户端中然后由客户端进行过滤。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">col</span> <span class="keyword">IS</span> <span class="literal">NULL</span>;</span><br></pre></td></tr></table></figure>
<p>下表显示了 WHERE 子句可用的操作符</p>
<table>
<thead>
<tr>
<th>操作符</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>= &lt;  &gt;</td>
<td>等于 小于 大于</td>
</tr>
<tr>
<td>&lt;&gt; !=</td>
<td>不等于</td>
</tr>
<tr>
<td>&lt;= !&gt;</td>
<td>小于等于</td>
</tr>
<tr>
<td>&gt;= !&lt;</td>
<td>大于等于</td>
</tr>
<tr>
<td>BETWEEN</td>
<td>在两个值之间</td>
</tr>
<tr>
<td>IS NULL</td>
<td>为NULL值</td>
</tr>
</tbody>
</table>
<p>应该注意到，NULL 与 0 、空字符串都不同。</p>
<p><strong>AND OR</strong>  用于连接多个过滤条件。优先处理 AND，因此当一个过滤表达式涉及到多个 AND 和 OR 时，应当使用 () 来决定优先级。</p>
<p><strong>IN</strong>  操作符用于匹配一组值，其后也可以接一个 SELECT 子句，从而匹配子查询得到的一组值。</p>
<p><strong>NOT</strong>  操作符用于否定一个条件。</p>
<h1 id="通配符"><a href="#通配符" class="headerlink" title="通配符"></a>通配符</h1><p>通配符也是用在过滤语句中，但它只能用于文本字段。</p>
<ul>
<li><p><strong>%</strong>  匹配 &gt;=0 个任意字符，类似于 *；</p>
</li>
<li><p><strong>_</strong>  匹配 ==1 个任意字符，类似于 .；</p>
</li>
<li><p><strong>[ ]</strong>  可以匹配集合内的字符，例如 [ab] 将匹配字符 a 或者 b。用脱字符 ^ 可以对其进行否定，也就是不匹配集合内的字符。</p>
</li>
</ul>
<p>使用 Like 来进行通配符匹配。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">col</span> <span class="keyword">LIKE</span> <span class="string">'[^AB]%'</span> <span class="comment">-- 不以 A 和 B 开头的任意文本</span></span><br></pre></td></tr></table></figure>
<p>不要滥用通配符，通配符位于开头处匹配会非常慢。</p>
<h1 id="计算字段"><a href="#计算字段" class="headerlink" title="计算字段"></a>计算字段</h1><p>在数据库服务器上完成数据的转换和格式化的工作往往比客户端上快得多，并且转换和格式化后的数据量更少的话可以减少网络通信量。</p>
<p>计算字段通常需要使用  <strong>AS</strong>  来取别名，否则输出的时候字段名为计算表达式。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col1*col2 <span class="keyword">AS</span> <span class="keyword">alias</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br></pre></td></tr></table></figure>
<p><strong>Concat()</strong>  用于连接两个字段。许多数据库会使用空格把一个值填充为列宽，因此连接的结果会出现一些不必要的空格，使用 <strong>TRIM()</strong> 可以去除首尾空格。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">Concat</span>(<span class="keyword">TRIM</span>(col1), <span class="string">' ('</span>, <span class="keyword">TRIM</span>(col2), <span class="string">')'</span>)</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br></pre></td></tr></table></figure>
<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><p>各个 DBMS 的函数都是不相同的，因此不可移植。</p>
<h2 id="文本处理"><a href="#文本处理" class="headerlink" title="文本处理"></a>文本处理</h2><table>
<thead>
<tr>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>LEFT() RIGHT()</td>
<td>左边或者右边的字符</td>
</tr>
<tr>
<td>LOWER() UPPER()</td>
<td>转换为小写或者大写</td>
</tr>
<tr>
<td>LTRIM() RTIM()</td>
<td>去除左边或者右边的空格</td>
</tr>
<tr>
<td>LENGTH()</td>
<td>长度</td>
</tr>
<tr>
<td>SUNDEX()</td>
<td>转换为语音值</td>
</tr>
</tbody>
</table>
<p>其中， <strong>SOUNDEX()</strong>  是将一个字符串转换为描述其语音表示的字母数字模式的算法，它是根据发音而不是字母比较。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">SOUNDEX</span>(col1) = <span class="keyword">SOUNDEX</span>(<span class="string">'apple'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="日期和时间处理"><a href="#日期和时间处理" class="headerlink" title="日期和时间处理"></a>日期和时间处理</h2><ul>
<li>日期格式：YYYY-MM-DD</li>
<li>时间格式：HH:MM:SS</li>
</ul>
<table>
<thead>
<tr>
<th>函 数</th>
<th>说 明</th>
</tr>
</thead>
<tbody>
<tr>
<td>AddDate()</td>
<td>增加一个日期（天、周等）</td>
</tr>
<tr>
<td>AddTime()</td>
<td>增加一个时间（时、分等）</td>
</tr>
<tr>
<td>CurDate()</td>
<td>返回当前日期</td>
</tr>
<tr>
<td>CurTime()</td>
<td>返回当前时间</td>
</tr>
<tr>
<td>Date()</td>
<td>返回日期时间的日期部分</td>
</tr>
<tr>
<td>DateDiff()</td>
<td>计算两个日期之差</td>
</tr>
<tr>
<td>Date_Add()</td>
<td>高度灵活的日期运算函数</td>
</tr>
<tr>
<td>Date_Format()</td>
<td>返回一个格式化的日期或时间串</td>
</tr>
<tr>
<td>Day()</td>
<td>返回一个日期的天数部分</td>
</tr>
<tr>
<td>DayOfWeek()</td>
<td>对于一个日期，返回对应的星期几</td>
</tr>
<tr>
<td>Hour()</td>
<td>返回一个时间的小时部分</td>
</tr>
<tr>
<td>Minute()</td>
<td>返回一个时间的分钟部分</td>
</tr>
<tr>
<td>Month()</td>
<td>返回一个日期的月份部分</td>
</tr>
<tr>
<td>Now()</td>
<td>返回当前日期和时间</td>
</tr>
<tr>
<td>Second()</td>
<td>返回一个时间的秒部分</td>
</tr>
<tr>
<td>Time()</td>
<td>返回一个日期时间的时间部分</td>
</tr>
<tr>
<td>Year()</td>
<td>返回一个日期的年份部分</td>
</tr>
</tbody>
</table>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SELECT NOW();</span><br><span class="line">        -&gt; '2017-06-28 14:01:52'</span><br></pre></td></tr></table></figure>
<h2 id="数值处理"><a href="#数值处理" class="headerlink" title="数值处理"></a>数值处理</h2><table>
<thead>
<tr>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>SIN()</td>
<td>正弦</td>
</tr>
<tr>
<td>COS()</td>
<td>余弦</td>
</tr>
<tr>
<td>TAN()</td>
<td>正切</td>
</tr>
<tr>
<td>ABS()</td>
<td>绝对值</td>
</tr>
<tr>
<td>SQRT()</td>
<td>平方根</td>
</tr>
<tr>
<td>MOD()</td>
<td>余数</td>
</tr>
<tr>
<td>EXP()</td>
<td>指数</td>
</tr>
<tr>
<td>PI()</td>
<td>圆周率</td>
</tr>
<tr>
<td>RAND()</td>
<td>随机数</td>
</tr>
</tbody>
</table>
<h2 id="汇总"><a href="#汇总" class="headerlink" title="汇总"></a>汇总</h2><table>
<thead>
<tr>
<th>函 数</th>
<th>说 明</th>
</tr>
</thead>
<tbody>
<tr>
<td>AVG()</td>
<td>返回某列的平均值</td>
</tr>
<tr>
<td>COUNT()</td>
<td>返回某列的行数</td>
</tr>
<tr>
<td>MAX()</td>
<td>返回某列的最大值</td>
</tr>
<tr>
<td>MIN()</td>
<td>返回某列的最小值</td>
</tr>
<tr>
<td>SUM()</td>
<td>返回某列值之和</td>
</tr>
</tbody>
</table>
<p>AVG() 会忽略 NULL 行。</p>
<p>使用 DISTINCT 可以汇总函数值汇总不同的值。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">AVG</span>(<span class="keyword">DISTINCT</span> col1) <span class="keyword">AS</span> avg_col</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br></pre></td></tr></table></figure>
<h1 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h1><p>分组就是把具有相同的数据值的行放在同一组中。</p>
<p>可以对同一分组数据使用汇总函数进行处理，例如求分组数据的平均值等。</p>
<p>指定的分组字段除了能让数组按该字段进行分组，也可以按该字段进行排序，例如按 col 字段排序并分组数据：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">col</span>, <span class="keyword">COUNT</span>(*) <span class="keyword">AS</span> <span class="keyword">num</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> <span class="keyword">col</span>;</span><br></pre></td></tr></table></figure>
<p>WHERE 过滤行，HAVING 过滤分组。行过滤应当先与分组过滤；</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">col</span>, <span class="keyword">COUNT</span>(*) <span class="keyword">AS</span> <span class="keyword">num</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">col</span> &gt; <span class="number">2</span></span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> <span class="keyword">col</span></span><br><span class="line"><span class="keyword">HAVING</span> <span class="keyword">COUNT</span>(*) &gt;= <span class="number">2</span>;</span><br></pre></td></tr></table></figure>
<p>GROUP BY 的排序结果为分组字段，而 ORDER BY 也可以以聚集字段来进行排序。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">col</span>, <span class="keyword">COUNT</span>(*) <span class="keyword">AS</span> <span class="keyword">num</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> <span class="keyword">col</span></span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> <span class="keyword">num</span>;</span><br></pre></td></tr></table></figure>
<p>分组规定：</p>
<ol>
<li>GROUP BY 子句出现在 WHERE 子句之后，ORDER BY 子句之前；</li>
<li>除了汇总计算语句的字段外，SELECT 语句中的每一字段都必须在 GROUP BY 子句中给出；</li>
<li>NULL 的行会单独分为一组；</li>
<li>大多数 SQL 实现不支持 GROUP BY 列具有可变长度的数据类型。</li>
</ol>
<h1 id="子查询"><a href="#子查询" class="headerlink" title="子查询"></a>子查询</h1><p>子查询中只能返回一个字段的数据。</p>
<p>可以将子查询的结果作为 WHRER 语句的过滤条件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SELECT *</span><br><span class="line">FROM mytable1</span><br><span class="line">WHERE col1 IN (SELECT col2</span><br><span class="line">                 FROM mytable2);</span><br></pre></td></tr></table></figure>
<p>下面的语句可以检索出客户的订单数量，子查询语句会对第一个查询检索出的每个客户执行一次：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> cust_name, (<span class="keyword">SELECT</span> <span class="keyword">COUNT</span>(*)</span><br><span class="line">                   <span class="keyword">FROM</span> Orders</span><br><span class="line">                   <span class="keyword">WHERE</span> Orders.cust_id = Customers.cust_id)</span><br><span class="line">                   <span class="keyword">AS</span> orders_num</span><br><span class="line"><span class="keyword">FROM</span> Customers</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> cust_name;</span><br></pre></td></tr></table></figure>
<h1 id="连接"><a href="#连接" class="headerlink" title="连接"></a>连接</h1><p>连接用于连接多个表，使用 JOIN 关键字，并且条件语句使用 ON 而不是 Where。</p>
<p>连接可以替换子查询，并且比子查询的效率一般会更快。</p>
<p>可以用 AS 给列名、计算字段和表名取别名，给表名取别名是为了简化 SQL 语句以及连接相同表。</p>
<h2 id="内连接"><a href="#内连接" class="headerlink" title="内连接"></a>内连接</h2><p>内连接又称等值连接，使用 INNER JOIN 关键字。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> a, b, c</span><br><span class="line"><span class="keyword">from</span> A <span class="keyword">inner</span> <span class="keyword">join</span> B</span><br><span class="line"><span class="keyword">on</span> A.key = B.key</span><br></pre></td></tr></table></figure>
<p>可以不明确使用 INNER JOIN，而使用普通查询并在 WHERE 中将两个表中要连接的列用等值方法连接起来。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> a, b, c</span><br><span class="line"><span class="keyword">from</span> A, B</span><br><span class="line"><span class="keyword">where</span> A.key = B.key</span><br></pre></td></tr></table></figure>
<p>在没有条件语句的情况下返回笛卡尔积。</p>
<h2 id="自连接"><a href="#自连接" class="headerlink" title="自连接"></a>自连接</h2><p>自连接可以看成内连接的一种，只是连接的表是自身而已。</p>
<p>一张员工表，包含员工姓名和员工所属部门，要找出与 Jim 处在同一部门的所有员工姓名。</p>
<p><strong>子查询版本</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="keyword">name</span></span><br><span class="line"><span class="keyword">from</span> employee</span><br><span class="line"><span class="keyword">where</span> department = (</span><br><span class="line">      <span class="keyword">select</span> department</span><br><span class="line">      <span class="keyword">from</span> employee</span><br><span class="line">      <span class="keyword">where</span> <span class="keyword">name</span> = <span class="string">"Jim"</span>);</span><br></pre></td></tr></table></figure>
<p><strong>自连接版本</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="keyword">name</span></span><br><span class="line"><span class="keyword">from</span> employee <span class="keyword">as</span> e1, employee <span class="keyword">as</span> e2</span><br><span class="line"><span class="keyword">where</span> e1.department = e2.department</span><br><span class="line">      <span class="keyword">and</span> e1.name = <span class="string">"Jim"</span>;</span><br></pre></td></tr></table></figure>
<p>连接一般比子查询的效率高。</p>
<h2 id="自然连接"><a href="#自然连接" class="headerlink" title="自然连接"></a>自然连接</h2><p>自然连接是把同名列通过等值测试连接起来的，同名列可以有多个。</p>
<p>内连接和自然连接的区别：内连接提供连接的列，而自然连接自动连接所有同名列。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employee <span class="keyword">natural</span> <span class="keyword">join</span> department;</span><br></pre></td></tr></table></figure>
<h2 id="外连接"><a href="#外连接" class="headerlink" title="外连接"></a>外连接</h2><p>外连接保留了没有关联的那些行。分为左外连接，右外连接以及全外连接，左外连接就是保留左表没有关联的行。</p>
<p>检索所有顾客的订单信息，包括还没有订单信息的顾客。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> Customers.cust_id, Orders.order_num</span><br><span class="line">   <span class="keyword">from</span> Customers <span class="keyword">left</span> <span class="keyword">outer</span> <span class="keyword">join</span> Orders</span><br><span class="line">   <span class="keyword">on</span> Customers.cust_id = Orders.curt_id;</span><br></pre></td></tr></table></figure>
<p>如果需要统计顾客的订单数，使用聚集函数。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> Customers.cust_id,</span><br><span class="line">       <span class="keyword">COUNT</span>(Orders.order_num) <span class="keyword">as</span> num_ord</span><br><span class="line"><span class="keyword">from</span> Customers <span class="keyword">left</span> <span class="keyword">outer</span> <span class="keyword">join</span> Orders</span><br><span class="line"><span class="keyword">on</span> Customers.cust_id = Orders.curt_id</span><br><span class="line"><span class="keyword">group</span> <span class="keyword">by</span> Customers.cust_id;</span><br></pre></td></tr></table></figure>
<h1 id="组合查询"><a href="#组合查询" class="headerlink" title="组合查询"></a>组合查询</h1><p>使用  <strong>UNION</strong>  来组合两个查询，如果第一个查询返回 M 行，第二个查询返回 N 行，那么组合查询的结果为 M+N 行。</p>
<p>每个查询必须包含相同的列、表达式或者聚集函数。</p>
<p>默认会去除相同行，如果需要保留相同行，使用 UNION ALL。</p>
<p>只能包含一个 ORDER BY 子句，并且必须位于语句的最后。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">col</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">col</span> = <span class="number">1</span></span><br><span class="line"><span class="keyword">UNION</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">col</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> <span class="keyword">col</span> =<span class="number">2</span>;</span><br></pre></td></tr></table></figure>
<h1 id="视图"><a href="#视图" class="headerlink" title="视图"></a>视图</h1><p>视图是虚拟的表，本身不包含数据，也就不能对其进行索引操作。对视图的操作和对普通表的操作一样。</p>
<p>视图具有如下好处：</p>
<ol>
<li>简化复杂的 SQL 操作，比如复杂的联结；</li>
<li>只使用实际表的一部分数据；</li>
<li>通过只给用户访问视图的权限，保证数据的安全性；</li>
<li>更改数据格式和表示。</li>
</ol>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">VIEW</span> myview <span class="keyword">AS</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">Concat</span>(col1, col2) <span class="keyword">AS</span> concat_col, col3*col4 <span class="keyword">AS</span> count_col</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col5 = val;</span><br></pre></td></tr></table></figure>
<h1 id="存储过程"><a href="#存储过程" class="headerlink" title="存储过程"></a>存储过程</h1><p>存储过程可以看成是对一系列 SQL 操作的批处理；</p>
<p><strong>使用存储过程的好处</strong></p>
<ol>
<li>代码封装，保证了一定的安全性；</li>
<li>代码复用；</li>
<li>由于是预先编译，因此具有很高的性能。</li>
</ol>
<p><strong>创建存储过程</strong></p>
<p>命令行中创建存储过程需要自定义分隔符，因为命令行是以 ; 为结束符，而存储过程中也包含了分号，因此会错误把这部分分号当成是结束符，造成语法错误。</p>
<p>包含 in、out 和 inout 三种参数。</p>
<p>给变量赋值都需要用 select into 语句。</p>
<p>每次只能给一个变量赋值，不支持集合的操作。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">delimiter //</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">procedure</span> myprocedure( <span class="keyword">out</span> ret <span class="built_in">int</span> )</span><br><span class="line">    <span class="keyword">begin</span></span><br><span class="line">        <span class="keyword">declare</span> y <span class="built_in">int</span>;</span><br><span class="line">        <span class="keyword">select</span> <span class="keyword">sum</span>(col1)</span><br><span class="line">        <span class="keyword">from</span> mytable</span><br><span class="line">        <span class="keyword">into</span> y;</span><br><span class="line">        <span class="keyword">select</span> y*y <span class="keyword">into</span> ret;</span><br><span class="line">    <span class="keyword">end</span> //</span><br><span class="line">delimiter ;</span><br></pre></td></tr></table></figure>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">call</span> myprocedure(@ret);</span><br><span class="line"><span class="keyword">select</span> @ret;</span><br></pre></td></tr></table></figure>
<h1 id="游标"><a href="#游标" class="headerlink" title="游标"></a>游标</h1><p>在存储过程中使用游标可以对一个结果集进行移动遍历。</p>
<p>游标主要用于交互式应用，其中用户需要对数据集中的任意行进行浏览和修改。</p>
<p><strong>使用游标的四个步骤：</strong></p>
<ol>
<li>声明游标，这个过程没有实际检索出数据；</li>
<li>打开游标；</li>
<li>取出数据；</li>
<li>关闭游标；</li>
</ol>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">delimiter //</span><br><span class="line"><span class="keyword">create</span> <span class="keyword">procedure</span> myprocedure(<span class="keyword">out</span> ret <span class="built_in">int</span>)</span><br><span class="line">    <span class="keyword">begin</span></span><br><span class="line">        <span class="keyword">declare</span> done <span class="built_in">boolean</span> <span class="keyword">default</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">declare</span> mycursor <span class="keyword">cursor</span> <span class="keyword">for</span></span><br><span class="line">        <span class="keyword">select</span> col1 <span class="keyword">from</span> mytable;</span><br><span class="line">        # 定义了一个continue handler，当 sqlstate '02000' 这个条件出现时，会执行 set done = 1</span><br><span class="line">        <span class="keyword">declare</span> continue <span class="keyword">handler</span> <span class="keyword">for</span> <span class="keyword">sqlstate</span> <span class="string">'02000'</span> <span class="keyword">set</span> done = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        open mycursor;</span><br><span class="line"></span><br><span class="line">        repeat</span><br><span class="line">            fetch mycursor into ret;</span><br><span class="line">            <span class="keyword">select</span> ret;</span><br><span class="line">        until done <span class="keyword">end</span> <span class="keyword">repeat</span>;</span><br><span class="line"></span><br><span class="line">        close mycursor;</span><br><span class="line">    <span class="keyword">end</span> //</span><br><span class="line"> delimiter ;</span><br></pre></td></tr></table></figure>
<h1 id="触发器"><a href="#触发器" class="headerlink" title="触发器"></a>触发器</h1><p>触发器会在某个表执行以下语句时而自动执行：DELETE、INSERT、UPDATE</p>
<p>触发器必须指定在语句执行之前还是之后自动执行，之前执行使用 BEFORE 关键字，之后执行使用 AFTER 关键字。BEFORE 用于数据验证和净化。</p>
<p>INSERT 触发器包含一个名为 NEW 的虚拟表。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TRIGGER</span> mytrigger <span class="keyword">AFTER</span> <span class="keyword">INSERT</span> <span class="keyword">ON</span> mytable</span><br><span class="line"><span class="keyword">FOR</span> <span class="keyword">EACH</span> <span class="keyword">ROW</span> <span class="keyword">SELECT</span> NEW.col;</span><br></pre></td></tr></table></figure>
<p>DELETE 触发器包含一个名为 OLD 的虚拟表，并且是只读的。</p>
<p>UPDATE 触发器包含一个名为 NEW 和一个名为 OLD 的虚拟表，其中 NEW 是可以被修改地，而 OLD 是只读的。</p>
<p>可以使用触发器来进行审计跟踪，把修改记录到另外一张表中。</p>
<p>MySQL 不允许在触发器中使用 CALL 语句 ，也就是不能调用存储过程。</p>
<h1 id="事务处理"><a href="#事务处理" class="headerlink" title="事务处理"></a>事务处理</h1><p><strong>基本术语</strong></p>
<ol>
<li>事务（transaction）指一组 SQL 语句；</li>
<li>回退（rollback）指撤销指定 SQL 语句的过程；</li>
<li>提交（commit）指将未存储的 SQL 语句结果写入数据库表；</li>
<li>保留点（savepoint）指事务处理中设置的临时占位符（placeholder），你可以对它发布回退（与回退整个事务处理不同）。</li>
</ol>
<p>不能回退 SELECT 语句，回退 SELECT 语句也没意义；也不能回退 CRETE 和 DROP 语句。</p>
<p>MySQL 的事务提交默认是隐式提交，也就是每执行一条语句就把这条语句当成一个事务然后进行提交。当出现 START TRANSACTION 语句时，会关闭隐式提交；当 COMMIT 或 ROLLBACK 语句执行后，事务会自动关闭，重新恢复隐式提交。</p>
<p>通过设置 autocommit 为 0 可以取消自动提交，直到 autocommit 被设置为 1 才会提交；autocommit 标记是针对每个连接而不是针对服务器的。</p>
<p>如果没有设置保留点，ROLLBACK 会回退到 START TRANSACTION 语句处；如果设置了保留点，并且在 ROLLBACK 中指定该保留点，则会回退到该保留点。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">START</span> <span class="keyword">TRANSACTION</span></span><br><span class="line">// ...</span><br><span class="line"><span class="keyword">SAVEPOINT</span> delete1</span><br><span class="line">// ...</span><br><span class="line"><span class="keyword">ROLLBACK</span> <span class="keyword">TO</span> delete1</span><br><span class="line">// ...</span><br><span class="line"><span class="keyword">COMMIT</span></span><br></pre></td></tr></table></figure>
<h1 id="字符集"><a href="#字符集" class="headerlink" title="字符集"></a>字符集</h1><p><strong>基本术语</strong></p>
<ol>
<li>字符集为字母和符号的集合；</li>
<li>编码为某个字符集成员的内部表示；</li>
<li>校对字符指定如何比较，主要用于排序和分组。</li>
</ol>
<p>除了给表指定字符集和校对外，也可以给列指定：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line">(<span class="keyword">col</span> <span class="built_in">VARCHAR</span>(<span class="number">10</span>) <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> latin <span class="keyword">COLLATE</span> latin1_general_ci )</span><br><span class="line"><span class="keyword">DEFAULT</span> <span class="built_in">CHARACTER</span> <span class="keyword">SET</span> hebrew <span class="keyword">COLLATE</span> hebrew_general_ci;</span><br></pre></td></tr></table></figure>
<p>可以在排序、分组时指定校对：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> *</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> <span class="keyword">col</span> <span class="keyword">COLLATE</span> latin1_general_ci;</span><br></pre></td></tr></table></figure>
<h1 id="权限管理"><a href="#权限管理" class="headerlink" title="权限管理"></a>权限管理</h1><p>MySQL 的账户信息保存在 mysql 这个数据库中。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">USE</span> mysql;</span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">user</span> <span class="keyword">FROM</span> <span class="keyword">user</span>;</span><br></pre></td></tr></table></figure>
<p><strong>创建账户</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">USER</span> myuser <span class="keyword">IDENTIFIED</span> <span class="keyword">BY</span> <span class="string">'mypassword'</span>;</span><br></pre></td></tr></table></figure>
<p>新创建的账户没有任何权限。</p>
<p><strong>修改账户名</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">RENAME</span> myuser <span class="keyword">TO</span> newuser;</span><br></pre></td></tr></table></figure>
<p><strong>删除账户</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">USER</span> myuser;</span><br></pre></td></tr></table></figure>
<p><strong>查看权限</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SHOW</span> <span class="keyword">GRANTS</span> <span class="keyword">FOR</span> myuser;</span><br></pre></td></tr></table></figure>
<p><strong>授予权限</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">GRANT</span> <span class="keyword">SELECT</span>, <span class="keyword">INSERT</span> <span class="keyword">ON</span> mydatabase.* <span class="keyword">TO</span> myuser;</span><br></pre></td></tr></table></figure>
<p>账户用 username@host 的形式定义，username@% 使用的是默认主机名。</p>
<p><strong>删除权限</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">REVOKE</span> <span class="keyword">SELECT</span>, <span class="keyword">INSERT</span> <span class="keyword">ON</span> mydatabase.* <span class="keyword">FROM</span> myuser;</span><br></pre></td></tr></table></figure>
<p>GRANT 和 REVOKE 可在几个层次上控制访问权限：</p>
<ul>
<li>整个服务器，使用 GRANT ALL 和 REVOKE ALL；</li>
<li>整个数据库，使用 ON database.*；</li>
<li>特定的表，使用 ON database.table；</li>
<li>特定的列；</li>
<li>特定的存储过程。</li>
</ul>
<p><strong>更改密码</strong></p>
<p>必须使用 Password() 函数</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SET</span> PASSWROD <span class="keyword">FOR</span> myuser = <span class="keyword">Password</span>(<span class="string">'newpassword'</span>);</span><br></pre></td></tr></table></figure>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ul>
<li>转载自<a href="https://github.com/CyC2018" target="_blank" rel="noopener">https://github.com/CyC2018</a></li>
</ul>

      
    </div>

    

    
    
    

    <div>
          
            
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/2018/03/16/SQL基础（转）/">SQL基础（转）</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Q.hongtao 的个人博客">Q.hongtao</a></p>
  <p><span>发布时间:</span>2018年03月16日 - 18:03</p>
  <p><span>最后更新:</span>2018年03月28日 - 11:03</p>
  <p><span>原始链接:</span><a href="/2018/03/16/SQL基础（转）/" title="SQL基础（转）">http://7ht.gitee.io/2018/03/16/SQL基础（转）/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://7ht.gitee.io/2018/03/16/SQL基础（转）/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>
</div>
<script>
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({
          title: "",
          text: '复制成功',
          icon: "success",
          showConfirmButton: true
          });
        });
    });
</script>


          
      </div>

    

    

    
  <div>
  
    

  
</div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SQL/" rel="tag"># SQL</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/16/分布式基础（转）/" rel="next" title="分布式基础（转）">
                <i class="fa fa-chevron-left"></i> 分布式基础（转）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/16/正则表达式（转）/" rel="prev" title="正则表达式（转）">
                正则表达式（转） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/head_cat.jpg"
                alt="Q.hongtao" />
            
              <p class="site-author-name" itemprop="name">Q.hongtao</p>
              <p class="site-description motion-element" itemprop="description">没有可怕的深度 就没有美丽的水面</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">34</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/ht-dep" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:15662728521@163.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基础"><span class="nav-number">1.</span> <span class="nav-text">基础</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#创建表"><span class="nav-number">2.</span> <span class="nav-text">创建表</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#插入"><span class="nav-number">3.</span> <span class="nav-text">插入</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#更新"><span class="nav-number">4.</span> <span class="nav-text">更新</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除"><span class="nav-number">5.</span> <span class="nav-text">删除</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#修改表"><span class="nav-number">6.</span> <span class="nav-text">修改表</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查询"><span class="nav-number">7.</span> <span class="nav-text">查询</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#排序"><span class="nav-number">8.</span> <span class="nav-text">排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#过滤"><span class="nav-number">9.</span> <span class="nav-text">过滤</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#通配符"><span class="nav-number">10.</span> <span class="nav-text">通配符</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#计算字段"><span class="nav-number">11.</span> <span class="nav-text">计算字段</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数"><span class="nav-number">12.</span> <span class="nav-text">函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#文本处理"><span class="nav-number">12.1.</span> <span class="nav-text">文本处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期和时间处理"><span class="nav-number">12.2.</span> <span class="nav-text">日期和时间处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数值处理"><span class="nav-number">12.3.</span> <span class="nav-text">数值处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#汇总"><span class="nav-number">12.4.</span> <span class="nav-text">汇总</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分组"><span class="nav-number">13.</span> <span class="nav-text">分组</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#子查询"><span class="nav-number">14.</span> <span class="nav-text">子查询</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#连接"><span class="nav-number">15.</span> <span class="nav-text">连接</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#内连接"><span class="nav-number">15.1.</span> <span class="nav-text">内连接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自连接"><span class="nav-number">15.2.</span> <span class="nav-text">自连接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自然连接"><span class="nav-number">15.3.</span> <span class="nav-text">自然连接</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#外连接"><span class="nav-number">15.4.</span> <span class="nav-text">外连接</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#组合查询"><span class="nav-number">16.</span> <span class="nav-text">组合查询</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#视图"><span class="nav-number">17.</span> <span class="nav-text">视图</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#存储过程"><span class="nav-number">18.</span> <span class="nav-text">存储过程</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#游标"><span class="nav-number">19.</span> <span class="nav-text">游标</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#触发器"><span class="nav-number">20.</span> <span class="nav-text">触发器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#事务处理"><span class="nav-number">21.</span> <span class="nav-text">事务处理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#字符集"><span class="nav-number">22.</span> <span class="nav-text">字符集</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#权限管理"><span class="nav-number">23.</span> <span class="nav-text">权限管理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考资料"><span class="nav-number">24.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ht-dep</span>

  

  
</div>



















        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.6"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.6"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.6"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.6"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.6"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  


<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"display":{"position":"right","width":100,"height":150},"model":{"jsonPath":"/live2dw/assets/tororo.model.json"},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":1,"opacityOnHover":0.2}});</script></body>
</html>
